<?php


namespace app\admin\controller;


use app\admin\common\helper\Response;
use app\admin\model\AuthRule;
use app\BaseController;
use think\facade\Db;
use think\facade\View;
use think\Request;

class Rule extends BaseController
{
    public function index(Request $request)
    {
        if ($request->isAjax()) {
            $result = AuthRule::order('sort_order', 'desc')->select();
            foreach ($result as $key=>$value){
                $value['open'] = true; //默认打开
            }
            $result_json = get_attr($result, 0);
            return json($result_json);
        }
        return View::fetch();

    }

    //下拉菜单
    public function select()
    {
        $res = AuthRule::field('id,id as value,title as name,parent_id,status')->where(['ismenu'=>1])->select();
        $result = toChildren($res, 'list');
        $data = [
            'code' => 0,
            'msg' => "获取成功",
            'trees' => $result
        ];
        return json($data);
    }

    //新增
    public function add(Request $request){
        if ($request->isAjax()){
            $rule = new AuthRule();
            $rule->save($request->param());
            return json(['code' => 200, 'url' => '', 'msg' => '添加成功！']);
        }
        return View::fetch();
    }


    //编辑
    public function edit(Request $request,$id)
    {
        $model = AuthRule::find($id);
        if ($request->isAjax()){
            if ($id == $request->post('parent_id')) {
                return json(['code' => 400, 'url' => '', 'msg' => '父级错误！']);
            }
            AuthRule::update($request->param());
            return json(['code' => 200, 'url' => '', 'msg' => '更新成功！']);
        }
        View::assign('model', $model);
        return View::fetch('edit');

    }

    //删除菜单
    public function del($id)
    {
        $auth = AuthRule::find($id);
        $auth->delete();
        return json(['code' => 200, 'url' => '', 'msg' => '删除成功！']);
    }

    //状态开关
    public function checkStatus(Request $request)
    {
        AuthRule::update($request->param());
        return json(['code' => 200, 'url' => '', 'msg' => '更新成功！']);
    }
}